package com.baway.login.vm

import androidx.lifecycle.MutableLiveData
import com.baway.common.entity.UserEntity
import com.baway.common.vm.BaseViewModel
import com.baway.db.entity.UserInfoEntity
import com.baway.login.model.LoginRepository
import com.tencent.mmkv.MMKV
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * Author: Jason Zhang
 * Date: 2025/8/29
 * Desc: 登录VM层
 */
@HiltViewModel
class LoginViewModel @Inject constructor(private val repo: LoginRepository): BaseViewModel() {

    val mSuccess = MutableLiveData<UserEntity>()

    /**
     * 账号和密码登录
     */
    fun loginToServer(userName: String, pwd: String){
        mViewModelScope.launch(mDispatcher) {
            //采用解构方式获取返回字段
            val (code, data, message ) = repo.loginToServer(userName, pwd)
            if (code == 200){
                mSuccess.postValue(data.apply {
                    typeId = 1 //代表为登录返回
                })

                //保存一下Token
                MMKV.defaultMMKV().run {
                    encode("token", data.token)
                    encode("userId", data.id)
                }

                //保存到数据库中
                saveUserInfo(data)

            } else {
                mError.postValue("登录失败！！")
            }
        }
    }

    /**
     * 新账号注册
     */
    fun registerToServer(userName: String, pwd: String){
        mViewModelScope.launch(mDispatcher) {
            //采用解构方式获取返回字段
            val (code, data, message ) = repo.registerToServer(userName, pwd)
            if (code == 200){
                mSuccess.postValue(data.apply {
                    typeId = 0 //代表为注册
                })
            } else {
                mError.postValue("登录失败！！")
            }
        }
    }


    /**
     * 保存用户信息到数据库
     */
    private fun saveUserInfo(entity: UserEntity){
        mViewModelScope.launch(mDispatcher) {
            var userInfoEntity = UserInfoEntity(
                userId = entity.id,
                cTime = entity.ctime,
                isAuthor = entity.isAuthor,
                password = entity.password,
                userName = entity.username,
            )
            repo.saveUserInfoToRoom(userInfoEntity)
        }
    }

    /**
     * 从数据库中查询用户信息
     */
    private fun queryUserInfoFromRoom(userId: Int){
        mViewModelScope.launch(mDispatcher) {
            val entity = repo.queryUserInfoFromRoom(userId)

            val userEntity = UserEntity(
                ctime = entity.cTime,
                id = entity.userId,
                password = entity.password,
                username = entity.userName,
            )

            mSuccess.postValue(userEntity)

        }
    }






}